package org.testile.datasetmanipulation;

import java.util.HashMap;
import java.util.Map;
import javax.script.SimpleBindings;
import org.apache.commons.lang.Validate;
import org.dbunit.dataset.IDataSet;
import org.testile.dataset.scriptable.ScriptableDataSet;
import org.testile.dataset.scriptable.ScriptableDataSetConfig;

/**
 *
 * @author hvizmar
 */
public class ReplaceEngineWrapper implements DatasetWrapper {
	private final Map<String,Map<String,String>> replacements;

	public ReplaceEngineWrapper(Map<String, Map<String, String>> replacements) {
		this.replacements = replacements;
	}

	public static ReplaceEngineWrapper of(String name, Map<String,String> replacements) {
		return new ReplaceEngineWrapperBuilder().with(name, replacements).build();
	}

	public static ReplaceEngineWrapperBuilder with(String name, Map<String,String> replacements) {
		return new ReplaceEngineWrapperBuilder().with(name, replacements);
	}

	@Override
	public IDataSet wrap(IDataSet dataSet) {
		SimpleBindings bindings = new SimpleBindings();
		for (Map.Entry<String, Map<String, String>> entry : replacements.entrySet()) {
			bindings.put(entry.getKey(), entry.getValue());
		}

		ScriptableDataSetConfig replaceConfig = new ScriptableDataSetConfig("replace", "REPLACE:", bindings);
		ScriptableDataSet replaceDataSet = new ScriptableDataSet(dataSet, replaceConfig);

		return replaceDataSet;
	}

	/**
	 *
	 */
	public static class ReplaceEngineWrapperBuilder {
		private Map<String,Map<String,String>> replacements;

		ReplaceEngineWrapperBuilder() {
			replacements = new HashMap<String, Map<String, String>>();
		}

		ReplaceEngineWrapperBuilder with(String name, Map<String,String> replacements) {
			Validate.notNull(replacements, "Replacements map cannot be null.");
			// defensive copy
			Map<String, String> map = new HashMap<String, String>();
			map.putAll(replacements);
			this.replacements.put(name, map);

			return this;
		}

		ReplaceEngineWrapper build() {
			return new ReplaceEngineWrapper(replacements);
		}
	}
}
